//
//  PayBDController.m
//  PosApp
//
//  Created by 刘萍 on 2018/10/15.
//  Copyright © 2018年 李英新. All rights reserved.
//

#import "PayBDController.h"
#import "PayJieBController.h"

@interface PayBDController ()<AliPayDelegate>
@property (strong, nonatomic) IBOutlet UILabel *TypeLabel;


@end

@implementation PayBDController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSLog(@"shouquan");
    
    [self UpLoadDataOfPayData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"绑定账号";
    
}

- (void)UpLoadDataOfPayData{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc] init];
    [dic setObject:KUseriPhone forKey:@"phone"];
    
    [MainObjectWay PostWithMethod:@"account" andAction:@"User" andAddParam:YES parameters:dic success:^(id responseObject) {
        NSLog(@"请求的数据结果 = %@",responseObject);
        if ([MainObjectWay IsSucceedWithCode:responseObject[@"code"]]) {
            NSMutableArray * arr = responseObject[@"data"];
            if (arr.count == 0) {
                self.TypeLabel.text = @"未绑定";
                self.TypeLabel.textColor = KRGBColor(160, 160, 160);
                NSString * PayStr = [NSString stringWithFormat:@"0"];
                SetKAliPay(PayStr);
            }else{
                NSMutableDictionary * dic = arr[0];
                if ([dic[@"account_type"] isEqual:@"Alipay"]) {
                    self.TypeLabel.text = @"已绑定";
                    self.TypeLabel.textColor = KRGBColor(39, 201, 255);
                    NSString * PayStr = [NSString stringWithFormat:@"1"];
                    SetKAliPay(PayStr);
                }else{
                    self.TypeLabel.text = @"未绑定";
                    self.TypeLabel.textColor = KRGBColor(160, 160, 160);
                    NSString * PayStr = [NSString stringWithFormat:@"0"];
                    SetKAliPay(PayStr);
                }
            }
        }
        
    } failure:^(NSError *error) {
        NSLog(@"cuowu xini = %@",error);
    }];
}
- (IBAction)ClickOnBtnTo:(id)sender {
    if ([KAliPay isEqual:@"0"]) {
        NSMutableDictionary * dic = [[NSMutableDictionary alloc] init];
        [dic setObject:KUseriPhone forKey:@"phone"];
        
        [MainObjectWay PostWithMethod:@"sign" andAction:@"Member" andAddParam:YES parameters:dic success:^(id responseObject) {
            NSLog(@"返回信息 = %@",responseObject);
            if ([MainObjectWay IsSucceedWithCode:responseObject[@"code"]]) {
                NSString * appScheme = @"con.LYX.PosApp4";
                NSString * orderStr = [NSString stringWithFormat:@"%@",responseObject[@"data"][@"sign"]];
                AppDelegate * AppD = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                AppD.AliPaydelegate = self;
                [[AlipaySDK defaultService] auth_V2WithInfo:orderStr fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                    NSLog(@"返回信息 = %@",resultDic);
                    [self TurehandlderAliPayAuthInfo:resultDic[@"result"]];
                }];
                
            }
        } failure:^(NSError *error) {
            NSLog(@"错误信息 = %@",error);
        }];
        
    }else{
        PayJieBController * payc = [[PayJieBController alloc] init];
        [self.navigationController pushViewController:payc animated:YES];
    }
}


- (void)TurehandlderAliPayAuthInfo:(NSString *)result{
    
    NSLog(@"diaoyong e %@",result);
    
    NSString *authCode = nil;
    NSString *openId = nil;
    NSString *UserID = nil;
    
    if (result.length > 0) {
        NSArray *resultArr = [result componentsSeparatedByString:@"&"];
        for (NSString *subResult in resultArr) {
            if (subResult.length > 10 && [subResult hasPrefix:@"auth_code="]) {
                authCode = [subResult substringFromIndex:10];
                
            }
            if (subResult.length > 32 && [subResult hasPrefix:@"alipay_open_id="]) {
                openId = [subResult substringFromIndex:15];
            }
            
            if (subResult.length > 16 && [subResult hasPrefix:@"user_id="]) {
                UserID = [subResult substringFromIndex:8];
                
                NSLog(@"授权结果 authCode = %@, openId = %@, userID = %@", authCode?:@"", openId?:@"", UserID?:@"");
                
                NSMutableDictionary * dic = [[NSMutableDictionary alloc] init];
                [dic setObject:KUseriPhone forKey:@"phone"];
                [dic setObject:UserID forKey:@"auth_code"];
                [dic setObject:@"Alipay" forKey:@"account_type"];
                
                [MainObjectWay PostWithMethod:@"account_bind" andAction:@"User" andAddParam:YES parameters:dic success:^(id responseObject) {
                    
                    NSLog(@"绑定结果 = %@",responseObject);
                    NSLog(@"绑定结果信息 = %@",responseObject[@"msg"]);
                    
                    if ([MainObjectWay IsSucceedWithCode:responseObject[@"code"]]) {
//                        [_AliPaydelegate handlderAliPayAuthInfo:nil];
                        [self UpLoadDataOfPayData];
                    }else{
                        [MBProgressHUD showAlertViewWithText:@"授权失败"];
                    }
                    
                } failure:^(NSError *error) {
                    NSLog(@"错误信息 = %@",error);
                }];
               
            }
        }
    }
}


- (void)handlderAliPayAuthInfo:(NSString *)result{
    [self UpLoadDataOfPayData];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
